/*
 * @Author       : wfl
 * @LastEditors  : wfl
 * @description  :
 * @updateInfo   :
 * @Date         : 2023-03-02 09:54:42
 * @LastEditTime : 2023-04-03 10:58:54
 */
import fs from 'node:fs'
import spritesmith from 'vite-plugin-spritesmith'

export default function createSpritesmith(isBuild: boolean) {
  const spriteDirnames: string[] = []
  fs.readdirSync('src/assets/sprites').forEach(dirname => {
    if (fs.statSync(`src/assets/sprites/${dirname}`).isDirectory())
      spriteDirnames.push(dirname)
  })
  const plugin: any[] = []
  spriteDirnames.forEach(item => {
    plugin.push(
      spritesmith({
        watch: !isBuild,
        src: {
          cwd: `../../assets/sprites/${item}`,
          glob: '*.png'
        },
        target: {
          image: `../../assets/sprites/${item}.png`,
          css: [
            [
              `../../assets/sprites/_${item}.scss`,
              {
                format: 'handlebars_based_template'
              }
            ]
          ]
        },
        apiOptions: {
          cssImageRef: `@/assets/sprites/${item}.png`,
          spritesheet_info: {
            name: item,
            format: 'handlebars_based_template'
          }
        },
        customTemplates: {
          handlebars_based_template: './plop-templates/scss.template.hbs'
        },
        spritesmithOptions: {
          algorithm: 'binary-tree',
          padding: 10
        }
      })
    )
  })
  return plugin
}
